<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Controller;

use AuctionCore\Common\AjaxPage;
use AuctionCore\Common\Image;
use AuctionCore\Common\Util;
use AuctionCore\System\AuctionException;

/**
 * APP端轮播图管理
 *
 * @author Xmh
 */
class CarouselController extends BaseController
{
    private $carouselLogic;

    private $empId;

    public function __construct()
    {
        parent::__construct();

        $this->empId = $this->user_info['emp_id'];

        $this->carouselLogic = D('Carousel', 'Logic');

        //模板赋值
        $this->assign("emp_id", $this->empId);
    }

    public function index()
    {

        $this->display();
    }

    public function carouselList()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = [];
        $params['c_id'] = I('get.c_id/d');
        $params['type'] = I('get.type/d');
        $params['start_time'] = I('get.start_time');
        $params['end_time'] = I('get.end_time');
        $params['sort'] = I('get.sort/d');
        $params['title'] = I('get.remark', '', 'trim');
        $params['status'] = I('get.status/d');
        $params['platform'] = I('get.platform/d');
        //获取list
        $result = $this->carouselLogic->getCarouselList($page, $size, $params);
        $Page = new AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show();   // 分页显示输出
        //模板赋值
        $this->assign("p", $page);
        $this->assign('page', $show);   // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign('platform', $params['platform']);
        $this->display();
    }

    /**
     * 添加轮播图
     */
    public function addCarousel()
    {
        $platform = I('get.platform');
        $list = $this->carouselLogic->getCarouselByPlatform($platform);
        $sortPosition = [
            ['position' => 1, 'is_have' => 0],
            ['position' => 2, 'is_have' => 0],
            ['position' => 3, 'is_have' => 0],
            ['position' => 4, 'is_have' => 0],
            ['position' => 5, 'is_have' => 0],
            ['position' => 6, 'is_have' => 0]
        ];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $sortList[$k] = $v['sort'];
            }
            foreach ($sortList as $ks => $vs) {
                foreach ($sortPosition as $kp => $vp) {
                    if ($vs == $vp['position']) {
                        $sortPosition[$kp]['is_have'] = 1;
                    }
                }
            }
        }
        $scene = D('OrderScene', 'Logic')->getOrderSceneByStatus(1);
        $sceneList = [];
        if (!empty($scene)) {
            foreach ($scene as $k => $s) {
                $sceneList[$k]['scene_id'] = $s['scene_id'];
                $sceneList[$k]['name'] = $s['name'];
            }
        }
        $this->assign('scene_list', $sceneList);
        $this->assign('platform', $platform);
        $this->assign('sort_position', $sortPosition);
        $this->display();
    }

    public function addCarouselData()
    {
        $data['emp_id'] = $this->empId;
        $data['remark'] = I('post.title', '', 'trim');
        $data['focus_picture'] = I('post.focus_picture', '', 'trim');
        if (empty($data['focus_picture'])) {
            $this->helpJsonResult(400, "抱歉，焦点图未上传");
        }
        $data['type'] = I('post.type/d');
        $data['auth'] = I('post.auth/d', 2);
        if ($data['type'] == 1) {
            $data['scene_id'] = I('post.scene_id/d');
        } elseif ($data['type'] == 2) {
            $data['param_url'] = I('post.param_url', '', 'trim');
            if (empty($data['param_url'])) {
                $this->helpJsonResult(400, "抱歉，活动参数未填写");
            }
        }
        $data['platform'] = I('post.platform/d');
        $data['sort'] = I('post.sort/d');
        if (empty($data['sort'])) {
            $this->helpJsRedirect(400, "抱歉，排序不能为空");
        }
        $data['share_picture'] = I('post.share_picture', '');
        if (empty($data['share_picture'])) {
            $this->helpJsonResult(400, "抱歉，分享缩略图未上传");
        }
        $data['share_content'] = I('post.share_content', '', 'trim');
        $data['status'] = '1';
        $data['publish_time'] = date("Y-m-d H:i:s", time());
        $res = $this->carouselLogic->addCarousel($data);
        if ($res) {
            $this->helpJsonResult(200, '添加成功');
        } else {
            $this->helpJsonResult(500, '添加失败');
        }
    }

    /**
     * 修改轮播图
     */
    public function editCarousel()
    {
        $p = I("get.p");
        $cid = I('get.cid/d');
        $platform = I('get.platform');
        $list = $this->carouselLogic->getCarouselByPlatform($platform);
        $sortPosition = [
            ['position' => 1, 'is_have' => 0],
            ['position' => 2, 'is_have' => 0],
            ['position' => 3, 'is_have' => 0],
            ['position' => 4, 'is_have' => 0],
            ['position' => 5, 'is_have' => 0],
            ['position' => 6, 'is_have' => 0]
        ];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $sortList[$k] = $v['sort'];
            }
            foreach ($sortList as $ks => $vs) {
                foreach ($sortPosition as $kp => $vp) {
                    if ($vs == $vp['position']) {
                        $sortPosition[$kp]['is_have'] = 1;
                    }
                }
            }
        }
        $carousel = $this->carouselLogic->getCarouselById($cid);
        $scene = D('OrderScene', 'Logic')->getOrderSceneByStatus(1);
        $sceneList = [];
        if (!empty($scene)) {
            foreach ($scene as $k => $s) {
                $sceneList[$k]['scene_id'] = $s['scene_id'];
                $sceneList[$k]['name'] = $s['name'];
            }
        }
        $this->assign('carousel', $carousel);
        $this->assign('scene_list', $sceneList);
        $this->assign('p', $p);
        $this->assign('platform', $platform);
        $this->assign('sort_position', $sortPosition);
        $this->display();
    }

    public function editCarouselData()
    {
        $data['c_id'] = I('post.c_id/d');
        $data['emp_id'] = $this->empId;
        $data['remark'] = I('post.title', '', 'trim');
        $data['focus_picture'] = I('post.focus_picture', '', 'trim');
        if (empty($data['focus_picture'])) {
            $this->helpJsonResult(400, "抱歉，焦点图未上传");
        }
        $data['type'] = I('post.type/d');
        $data['auth'] = I('post.auth/d', 2);
        if ($data['type'] == 1) {
            $data['scene_id'] = I('post.scene_id/d');
        } elseif ($data['type'] == 2) {
            $data['param_url'] = I('post.param_url', '', 'trim');
            if (empty($data['param_url'])) {
                $this->helpJsonResult(400, "抱歉，活动参数未填写");
            }
        }
        $data['sort'] = I('post.sort/d');
        if (empty($data['sort'])) {
            $this->helpJsonResult(400, "抱歉，排序不能为空");
        }
        $data['share_picture'] = I('post.share_picture', '', 'trim');
        if (empty($data['share_picture'])) {
            $this->helpJsonResult(400, "抱歉，分享缩略图未上传");
        }
        $data['share_content'] = I('post.share_content', '', 'trim');
        $data['status'] = '2'; //编辑焦点图确定后状态为下线
        $res = $this->carouselLogic->saveCarousel($data);
        if ($res !== false) {
            $this->helpJsonResult(200, '修改成功');
        } else {
            $this->helpJsonResult(500, '修改失败');
        }
    }

    /**
     * 确认页面：不启用
     */
    public function confirmCarousel()
    {
        $data['focus_picture'] = I("post.focus_picture");
        $Carousel = [];
        $this->assign("Carousel", $Carousel);
        $this->display();
    }

    /**
     * 上线、下线操作
     */
    public function changeCarouselStatus()
    {
        try {
            $cId = I('post.c_id/d');
            $sort = I("post.sort/d");
            $status = I('post.status/d');
            $platform = I('post.platform/d');
            $res = $this->carouselLogic->updateCarouselStatus($cId, $sort, $status, $platform);
            if ($res) {
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => 200, 'msg' => '']);
            } else {
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => 500, 'msg' => '该位置已被占用，请重新上线']);
            }
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, ['msg' => $e->getMessage(), 'code' => $e->getCode()]);
            exit;
        }
    }

    /**
     * 上传图片
     */
    public function upload_pic_bak()
    {
        $pic = I('data.focus_picture', '', '', $_FILES);
        if (!empty($pic)) {
            $flag = true;
            if ($pic['error'] != 0) {
                $flag = false;
                $rep['msg'] = '照片上传失败';
                \Think\Log::record($rep['msg'] . ',错误码：' . $pic['error'] . ',time:' . date('Y-m-d H:i:s'));
            }
            //图片上传
            if ($flag) {
                $object = 'upload/' . create_uuid() . '.' . get_extension($pic['name']);
                $pic_path = $pic['tmp_name'];
                try {
                    $aliObject = Image::upload_file_by_file(OSS_BUCKET, $object, $pic_path);
                    $host = get_content_cdnurl();
                    $rep['data'] = $host . $aliObject;
                    $data['focus_picture'] = $rep['data'];
                } catch (\Exception $e) {
                    $rep['msg'] = $e->getMessage();
                }
                echo json_encode($data);
                exit();
            }
        }
    }

    public function uploadPic()
    {
        try {
            $ret = [];
            foreach ($_FILES as $key => $file) {
                $tmp_file = $file['tmp_name'];
                $object = $tmp_file . '.' . get_extension($file['name']);
                $ret[] = Image::upload_file_by_file(OSS_BUCKET, $object, $tmp_file, null, '', 'carousel');
            }
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '', 'data' => $ret]);
            exit;
        } catch (\Exception $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => $e->getMessage()]);
            exit;
        }
    }

    /**
     * 更新图片信息到数据库
     */
    public function uploadPicInfo()
    {
        try {
            $focusPicture = $_REQUEST['focus_picture'];
            if (!$focusPicture)
                AuctionException::make_throw('200009');
            $carousel['c_id'] = I("post.c_id/d");
            $carousel['focus_picture'] = $focusPicture;
            $this->carouselLogic->saveCarousel($carousel);

            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '']);
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '500', 'msg' => $e->getMessage()]);
            exit;
        }
    }

    /**
     * 判断排序是否在上线状态中的焦点图是否存在
     */
    public function isSortExist()
    {
        $sort = I("post.sort/d");
        $platform = I('post.platform/d');
        $count = $this->carouselLogic->isSortOnline($sort, $platform);
        echo json_encode(['code' => 200, 'count' => $count]);
    }

}
